#pragma once
#include "cybertron/network/Message.hpp"
#include "cybertron/network/SocketTcpClient.hpp"
#include "cybertron/network/SocketEventHandler.hpp"
#include "cybertron/network/NetworkActionExecuter.hpp"
#include "cybertron/network/MessageRouter.hpp"
#include "cybertron/core/Log.hpp"
#include <thread>
#include <iostream>
#include "Node/Agent.pb.h"

using namespace cybertron;

class AgentManage
{
public:
	AgentManage();
	~AgentManage();
	
	static AgentManage *GetInstance(){
		static AgentManage instance;
		return &instance;
	}
	bool initialize();
	bool startWebProcess();
	void killProcess();
	bool Stop();
private:
	bool startProcess();
	void zeroMembers();
	void run();
	void clearThis();
	bool Connect();
	void onDisconnected();
	void onServerMessage(Message& msg);	
public:
	void sendRegisterNode();
	void getAgentInitInfo();
	int bIsAgentConnectWeb() { return mbIsOnline; };
	void onFromMasterNodeRegisterRet(cybertron::Message& msg);
	void onFromSyncAgentPitInfoRet(cybertron::Message& msg);
	bool ReadAgentIdFromLocal(std::string& agentId);
	bool CheckLocalSystemAuthority();
	bool getAuthStatus() { return mbIsAuth; };
	int getOnlineStatus() { return mbIsOnline; };

	std::string getAuthCode() { return mAuthCode; };
	std::string getWebIP() { return mWebIP; };
	std::string getWebPort() { return mWebPort; };

	bool LoadAgentCfgFromLocal();
	bool SaveAgentCfgToLocal(std::string agentConfig);
	std::string GetAgentLogPath();
private:
protected:
	std::string mHostIp;
	int mHostPort;
	std::shared_ptr<SocketTcpClient> mpAgentClient;
	enum EServiceState
	{
		EServiceState_Work,
		EServiceState_Stop
	};
	std::atomic<EServiceState> mState;
	bool mbRecvThreadRun;
	bool mbRecvThreadExit;

	std::string mWebIP;
	std::string mWebPort;
	std::string mMasterIP;
	std::string mMasterPort;
	std::string mPublicIP;
	std::string mAgentPort;
	std::string mAuthCode;

	std::string mConfPath;
	std::string mAgentConfigPath;
	std::string mAgentServerLog;

	bool mbIsAuth;
	int mbIsOnline;
};
